﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using Zen.Barcode;

namespace Worktool
{
    public partial class Serials : Form
    {
        bool print = true;
        PrintDocument label;
        private string changedSerialNumber = "";
        private string changedManufacturer = "";
        private string changedModel = "";
        String pkInstalledPrinters;
                    


        public Serials()
        {
            InitializeComponent();
            this.Text = "Serials: " + Properties.Settings.Default.CurrentDBName; 
            this.vw_lbl_SerialsTableAdapter.updateSerials();
            this.vw_lbl_SerialsTableAdapter.Fill(this.aSCDataSet.vw_lbl_Serials);
            this.tbl_log_vw_lbl_SerialsTableAdapter.Fill(this.aSCDataSet.tbl_log_vw_lbl_Serials);
            // Eventhandler after the initialization
            this.dataGridView2.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView2_CellValueChanged);
            // Drucker in das Auswahlfeld eintragen
            for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
            {
                pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
                comboBox1.Items.Add(pkInstalledPrinters);
            }
            for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
            {
                if (Properties.Settings.Default.LabelPrinterName == PrinterSettings.InstalledPrinters[i])
                {
                    comboBox1.Text = Properties.Settings.Default.LabelPrinterName;
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        //
        //  Filter Datagrid
        //

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            {
                if (textBox1.Text == "" && textBox2.Text == "")
                {
                    vwlblSerialsBindingSource.Filter = null;
                }
                else if (textBox1.Text == "" && textBox2.Text != "")
                {
                    vwlblSerialsBindingSource.Filter = string.Format("model LIKE '{0}'", (textBox2.Text + "*"));
                }
                else if (textBox1.Text != "" && textBox2.Text == "")
                {
                    vwlblSerialsBindingSource.Filter = string.Format("manufacturer LIKE '{0}'", (textBox1.Text + "*"));
                }
                else if (textBox1.Text != "" && textBox2.Text != "")
                {
                    vwlblSerialsBindingSource.Filter = string.Format("manufacturer LIKE '{0}' AND model LIKE '{1}'", (textBox1.Text + "*"), (textBox2.Text + "*"));
                }
            }
        }

        //
        //  Export to Excel
        //
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            
        }

        //
        //  Write changed Values back to Database
        //
        private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)    
        {
            
            if (e.ColumnIndex == dataGridView2.Columns["serialNumber"].Index)
            {
                changedSerialNumber = dataGridView2.CurrentRow.Cells["serialNumber"].Value.ToString();
                changedManufacturer = dataGridView2.CurrentRow.Cells["Manufacturer"].Value.ToString();
                changedModel = dataGridView2.CurrentRow.Cells["Model"].Value.ToString();
                try
                {
                    dataGridView2.CurrentRow.Cells["serialDate"].Value = DateTime.Today;
                    dataGridView2.CurrentRow.Cells["serialUser"].Value = Properties.Settings.Default.User;
                    
                    this.tbl_log_vw_lbl_SerialsTableAdapter.Insert(Convert.ToInt32(dataGridView2.CurrentRow.Cells["Artikel_ID"].Value),
                                                   dataGridView2.CurrentRow.Cells["serialNumber"].Value.ToString(),
                                                   dataGridView2.CurrentRow.Cells["Manufacturer"].Value.ToString(),
                                                   dataGridView2.CurrentRow.Cells["Model"].Value.ToString(),
                                                   dataGridView2.CurrentRow.Cells["Description"].Value.ToString(),
                                                   Convert.ToDateTime(dataGridView2.CurrentRow.Cells["serialDate"].Value),
                                                   dataGridView2.CurrentRow.Cells["serialUser"].Value.ToString());
                    
                    this.vwlblSerialsBindingSource.EndEdit();
                    vw_lbl_SerialsTableAdapter.Update(aSCDataSet);
                    this.vw_lbl_SerialsTableAdapter.Fill(this.aSCDataSet.vw_lbl_Serials);
                }
                catch (Exception ex)
                {
                }


                // Label ausdrucken

                if (comboBox1.Text != "")
                {
                    label = new PrintDocument();
                    PaperSize pS = new PaperSize("Custom Size", 620, 290);
                    label.DefaultPageSettings.PaperSize = pS;
                    label.PrinterSettings.PrinterName = comboBox1.Text;
                    label.PrinterSettings.DefaultPageSettings.PaperSize = pS;
                    label.PrintPage += new PrintPageEventHandler(label_PrintPage);

                    if (print)
                    {
                        for (int i = 0; i < Convert.ToInt32(comboBox2.Text); i++)
                        {
                            label.Print();
                        }
                    }
                }
                
            
            
            }
        }

        //
        // Show Logfile
        //
        private void pictureBox4_Click(object sender, EventArgs e)
        {
            
        }

        //
        // Print Eventhandler
        //
        private void label_PrintPage(object sender, PrintPageEventArgs e)
        {

            SolidBrush brush = new SolidBrush(Color.Black);
            System.Drawing.Font header = new System.Drawing.Font(FontFamily.GenericSansSerif, 9.0F, FontStyle.Bold);
            Code128BarcodeDraw barcode128 = BarcodeDrawFactory.Code128WithChecksum;
            Image img;

            
                e.Graphics.DrawString("Manufacturer: " + changedManufacturer, header, brush, 5, 10);
                e.Graphics.DrawString("Model: " + changedModel, header, brush, 5, 30);
                e.Graphics.DrawString("SN: " + changedSerialNumber, header, brush, 5, 50);
                e.Graphics.DrawImage(Worktool.Properties.Resources.ASC_Logo_quadratisch, 200, 10, 30, 30);
                if (changedSerialNumber != null && changedSerialNumber != "")
                {
                    img = barcode128.Draw(changedSerialNumber, 30);
                    e.Graphics.DrawImage(img, 5, 70);
                }
            

        }     
        
        //
        // Drucken ein und ausschalten
        //
        private void button1_Click(object sender, EventArgs e)
        {
            if (print)
            {
                button1.Text = "Printing Off";
                button1.BackColor = Color.Red;
                print = !print;
            }
            else
            {
                button1.Text = "Printing On";
                button1.BackColor = Color.Green;
                print = !print;
            }
        }

        //
        // Aktuelles Label drucken
        //
        private void button2_Click(object sender, EventArgs e)
        {
            int a = 0;
            for (int i = 0; i < dataGridView2.SelectedCells.Count; i++)
            {
                
                a = dataGridView2.SelectedCells[i].RowIndex;
                changedSerialNumber = dataGridView2.Rows[a].Cells["serialNumber"].Value.ToString();
                changedManufacturer = dataGridView2.Rows[a].Cells["Manufacturer"].Value.ToString();
                changedModel = dataGridView2.Rows[a].Cells["Model"].Value.ToString();

                label = new PrintDocument();
                PaperSize pS = new PaperSize("Custom Size", 620, 290);
                label.DefaultPageSettings.PaperSize = pS;
                label.PrinterSettings.PrinterName = comboBox1.Text;
                label.PrinterSettings.DefaultPageSettings.PaperSize = pS;
                label.PrintPage += new PrintPageEventHandler(label_PrintPage);
                try
                {
                    label.Print();
                }
                catch (Exception ex)
                { 

                }
            }
        }

        //
        // Neuen Defaultprinter eintragen
        //
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.LabelPrinterName = comboBox1.Text;
            Properties.Settings.Default.Save();
                
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView2.SelectedCells.Count == 1)
            {
                Clipboard.SetText(dataGridView2.SelectedCells[0].Value.ToString());
            }
        }

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<int> zeilen = new List<int> { };
            for (int i = 0; i < dataGridView2.SelectedCells.Count; i++)
            {
                zeilen.Add(dataGridView2.SelectedCells[i].RowIndex);
            }
            if (Clipboard.GetText() != "")
            {
                for (int i = 0; i < zeilen.Count; i++)
                {
                    try
                    {
                        dataGridView2.Rows[zeilen[i]].Cells["SerialNumber"].Value = Clipboard.GetText();
                    }
                    catch (Exception ex)
                    { }
                }
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<int> zeilen = new List<int> { };
            for (int i = 0; i < dataGridView2.SelectedCells.Count; i++)
            {
                zeilen.Add(dataGridView2.SelectedCells[i].RowIndex);
            } 
            for (int i = 0; i < zeilen.Count; i++)
            {
                try
                {
                    if (dataGridView2.Rows[zeilen[i]].Cells["SerialNumber"].ValueType == typeof(string))
                    {
                        dataGridView2.Rows[zeilen[i]].Cells["SerialNumber"].Value = "";
                    }
                    if (dataGridView2.Rows[zeilen[i]].Cells["SerialNumber"].ValueType == typeof(int))
                    {
                        dataGridView2.Rows[zeilen[i]].Cells["SerialNumber"].Value = 0;
                    }
                    if (dataGridView2.Rows[zeilen[i]].Cells["SerialNumber"].ValueType == typeof(DateTime))
                    {
                        dataGridView2.Rows[zeilen[i]].Cells["SerialNumber"].Value = "";
                    }
                }
                catch (Exception ex)
                { }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            dataGridView2.SelectAll();
            DataObject dataObj = dataGridView2.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView2.ClearSelection();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Serials_log serials_log = new Serials_log();
            serials_log.Show();
        }


    }
}
